var utl = {};

utl.Binary = {
    fixdata(data) {
        var o = "",
            l = 0,
            w = 10240;
        for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
    },
    s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}
utl.XLSX = {
    wb: null,
    rABS: false,
    import(f, c) {
        this.wb = null;
        var reader = new FileReader();
        reader.onload = function (e) {
            var data = e.target.result;
            if (utl.XLSX.rABS) {
                utl.XLSX.wb = XLSX.read(btoa(utl.Binary.fixdata(data)), {
                    type: 'base64'
                });
            } else {
                utl.XLSX.wb = XLSX.read(data, {
                    type: 'binary'
                });
            }
            if (c && typeof (c)) {
                c();
            }
        };
        if (utl.XLSX.rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }
    },
    onImport(obj, c) {
        if (!obj.files) {
            return;
        }
        this.import(obj.files[0], c);
    },
    getSheetsByIndex(index = 0) {
        return XLSX.utils.sheet_to_json(this.wb.Sheets[this.wb.SheetNames[index]]);
    },
    getCharCol(n) {
        let temCol = '',
            s = '',
            m = 0
        while (n > 0) {
            m = n % 26 + 1
            s = String.fromCharCode(m + 64) + s
            n = (n - m) / 26
        }
        return s
    },
    export(json, title, type) {
        var keyMap = []; for (k in json[0]) {
            keyMap.push(k);
        }
        var tmpdata = []; json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
            v: v[k],
            position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
            v: v.v
        });
        var outputPos = Object.keys(tmpdata); var tmpWB = new Object();
        title = title ? title : "mySheet";
        tmpWB.SheetNames = [title];
        tmpWB.Sheets = {};
        tmpWB.Sheets[title] = Object.assign({}, tmpdata, {
            '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]
        });
        return new Blob([utl.Binary.s2ab(XLSX.write(tmpWB,
            { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }))], { type: "" });
    },
    onExport(json, title, type) {
        utl.Download.byObj(this.export(json, title, type), "下载.xlsx");
    }
};
utl.Download = {
    byURL(url, fileName) {
        var tmpa = document.createElement("a");
        tmpa.download = fileName || "下载";
        tmpa.href = url; tmpa.click();
    },
    byObj(obj, fileName) {
        this.byURL(URL.createObjectURL(obj), fileName);
        setTimeout(function () { URL.revokeObjectURL(obj); }, 100);
    }
}
utl.Object = {
    reverse(obj) {
        var o = new Object();
        for (var k in obj) {
            o[obj[k]] = k;
        }
        return o;
    },
    deepCopy() {
        let temp = obj.constructor === Array ? [] : {}
        for (let val in obj) {
            temp[val] = typeof obj[val] == 'object' ? deepCopy(obj[val]) : obj[val];
        }
        return temp;
    },
    copyJson(o) { return JSON.parse(JSON.stringify(o)); }
}

var hotElement = document.querySelector('#hot');
var colHeaders = [];
var cols = [];
var xHred = {};

var columnData = JSON.parse(window.localStorage.getItem("columnData"));

for (var key in columnData) {
    var columnT = columnData[key];
    console.log("columnT" + JSON.stringify(columnT));
    colHeaders.push(columnT['name']);
    cols.push({ data: columnT['data'], type: columnT['type'] });
    xHred[columnT['name']] = columnT['data'];
}

// console.log("colHeaders"+JSON.stringify(colHeaders))
// console.log("cols"+JSON.stringify(cols))
// console.log("xHred"+JSON.stringify(xHred))

function impt(emt) {
    utl.XLSX.onImport(emt, function () {
        var rt = utl.XLSX.getSheetsByIndex(); var tmp = [];
        rt.forEach(function (value, index, array) {
            var t = new Object();
            for (var k in value) {
                t[xHred[k]] = value[k];
            }
            tmp.push(t);
        });
        hot.loadData(tmp);
    });
}
function down() {
    var d = utl.Object.copyJson(hot.getSourceData())
    d.unshift(utl.Object.reverse(xHred));
    utl.XLSX.onExport(d);
}
function showData() {
    var tmp = [];
    hot.getSourceData().forEach(function (value, index, array) {
        var t = new Object();
        for (var k in value) {
            t[k] = filterVal[k] ? filterVal[k](value[k]) : value[k];
        }
        tmp.push(t);
    });
    alert(JSON.stringify(tmp));
    window.open("data:text/html;charset=utf-8," + JSON.stringify(tmp));
    console.log(tmp);
    return tmp;
}

function writeObj(obj) {
    var description = "";
    for (var i in obj) {
        var property = obj[i];
        description += i + " = " + property + "\n";
    }
    console.log("obj:" + description)
}


var Handson_renderer = function (instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
   
    for(var index in currentErrorMessage){
        var error = currentErrorMessage[index];
        console.log("error:"+JSON.stringify(error));
        if(error['errorPos'] == "table"){
            td.style.borderTop = '2px dashed #e50a0a';
            td.style.borderRight = '2px dashed #e50a0a';
            td.style.borderLeft = '2px dashed #e50a0a';
            td.style.borderBottom = '2px dashed #e50a0a';
            //td.style.backgroundColor ='#e50a0a';
            td.style.color = '#e50a0a';
            td.setAttribute('title',error["table"]);
            break;
        }else if(error['errorPos']==prop){
            console.log("进入")
            td.style.borderTop = '2px dashed #e50a0a';
            td.style.borderRight = '2px dashed #e50a0a';
            td.style.borderLeft = '2px dashed #e50a0a';
            //td.style.borderBottom = '2px dashed #e50a0a';
            //td.style.backgroundColor ='#e50a0a';
            td.style.color = '#e50a0a';
            td.setAttribute('title',error['col']);
        }else{
            var rowDataT = resourceData[row];
            var id = rowDataT['id'];
            var errorMS = error[prop];
            var errorRMs = error['row'];
            if(error['errorPos']===id){
                if(errorMS||errorRMs){
                    console.log("常规进入prop:"+JSON.stringify(prop));
                    console.log("常规进入error:"+JSON.stringify(error));
                    console.log("常规进入error[prop]:"+error[prop]);
                    console.log("常规进入:"+errorMS)
                    td.style.borderTop = '2px dashed #e50a0a';
                    td.style.borderLeft = '2px dashed #e50a0a';
                    td.style.borderBottom = '2px dashed #e50a0a';
                    //td.style.backgroundColor ='#e50a0a';
                    td.style.color = '#e50a0a';
                    if(errorMS){
                        td.setAttribute('title',errorMS); 
                    }
                    if(errorRMs){
                        td.setAttribute('title',errorRMs);
                    }
                   
                }
                
            }
        }

    }

    //instance.getCellMeta(row,clo);//根据行列索引获取单元格的属性对象
    //getCellRenderer(row,col)：//根据单元格的行列索引获取单元格的渲染函数
    //getCellValidator()：//获取单元格的校验器
    //getColHeader(col):根据列索引获取列头名称
    //etRowHeader(row):根据行索引获取行头名称
    //.getCoords(elem):获取元素的坐标
    //getCopyableData(startRow,startCol,endRow,endCol):获取指定范围的单元格数据
    //getData(row1,col1,row2,col2):获取指定范围的单元格的数据
    //getDataAtCell(row,col):根据行列索引获取单元格的值
    //getDataAtCol(col)：根据列索引获取一列的数据
     //getDataAtRow(row)：根据行索引获取一行的数据
};



var hotSettings = {
    colHeaders: colHeaders,
    data: [],
    columns: cols,
    autoWrapRow: true,
    minRows: 1,
    manualColumnResize: true,
    manualRowResize: true,
    stretchH: "all",
    manualColumnMove: true,
    manualRowMove: true,
    rowHeaders: true,
    columnSorting: true,
    sortIndicator: true,
    contextMenu: true,
    autoColumnSize: true,
    dropdownMenu: true,
    cells: function (row, col, prop) {
        var cellProperties = {};
        // if (row === 0 || this.instance.getData()[row][col] === 'readOnly') {  
        //     cellProperties.readOnly = true;  
        // }  

        cellProperties.renderer = Handson_renderer;//调用自定义渲染方法 


        return cellProperties;
    }

};
var hot = new Handsontable(hotElement, hotSettings);

Handsontable.dom.addEvent(save, 'click', function () {
    // save all cell's data
    console.log(hot.getData())
    $.ajax({
        method: "POST",
        url: "/api/savetonew",
        timeout: 10000,
        data: JSON.stringify({ data: hot.getData() }),
        async: false,
        headers: { "client-type": "platform", },
        dataType: "json",
        contentType: false,
        processData: false,//数据不做预处理
        success: function (res) {
            return;
        },
        error: function (e) {
            alert(e.msg);
        }
    })
});



